package com.jxb.myshop.dao.impl;

import com.jxb.myshop.dao.ItemDao;
import com.jxb.myshop.entity.Item;
import com.jxb.myshop.entity.vo.ItemVo;
import com.jxb.myshop.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class ItemDaoImpl implements ItemDao {
    private QueryRunner qr = new QueryRunner(DBUtil.getDs());

    @Override
    public int[] createItem(List<Item> itemList) throws SQLException {
        // 创建一个二维数组
        Object[][] items = new Object[itemList.size()][];
        // 遍历集合
        for (int i = 0; i < itemList.size(); i++) {
            items[i] = new Object[]{
                    itemList.get(i).getOid(),
                    itemList.get(i).getPid(),
                    itemList.get(i).getIcount(),
                    itemList.get(i).getInum()
            };
        }
        //batch 批量操作的方法
        //提供要批量操作的sql语句,提供二维数组的参数,外层高维数组代表对象的个数(数量),内层数组低维的数组,代表1个对象中的属性
        //int[] 保存每次操作的受影响行数
        int[] batch = qr.batch("insert into item values (default,?,?,?,?)", items);
        return batch;
    }

    @Override
    public List<ItemVo> getItemAndProduct(String oid) throws SQLException {
        return qr.query("select * from item i,product p where i.pid = p.pid and i.oid = ? ",
                new BeanListHandler<>(ItemVo.class),
                oid);
    }
}
